/**
 *
 */
package com.module.boots.coder.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Properties;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import lombok.extern.slf4j.Slf4j;

/**
 * 页面生成工具类
 * @author：溪云阁
 * @date：2020年9月3日
 */
@Slf4j
public class PageUtils {

    private static VelocityEngine ve;

    private static final String CONTENT_ENCODING = "UTF-8";

    private static boolean isReplace = true;

    static {
        try {
            final Properties properties = new Properties();
            properties.setProperty("resource.loader", "class");
            properties.setProperty("file.resource.loader.description", "Velocity File Resource Loader");
            properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            properties.setProperty("file.resource.loader.cache", "true");
            properties.setProperty("file.resource.loader.modificationCheckInterval", "30");
            properties.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.Log4JLogChute");
            properties.setProperty("runtime.log.logsystem.log4j.logger", "org.apache.velocity");
            properties.setProperty("directive.set.null.allowed", "true");
            final VelocityEngine velocityEngine = new VelocityEngine();
            velocityEngine.init(properties);
            PageUtils.ve = velocityEngine;
        }
        catch (final Exception e) {
            log.error(e.getLocalizedMessage());
        }
    }

    /**
     * 生成页面
     * @author 溪云阁
     * @param context 页面里面的内容
     * @param templateName 模板的地址加名字
     * @param filePath 文件的路径
     * void
     */
    public static void WriterPage(VelocityContext context, String templateName, String filePath) {
        try {
            final File file = new File(filePath);
            if (!file.exists()) {
                new File(file.getParent()).mkdirs();
            } else if (PageUtils.isReplace) {
                log.info("\u66FF\u6362\u6587\u4EF6:" + file.getAbsolutePath());
            }
            final Template template = PageUtils.ve.getTemplate(templateName, PageUtils.CONTENT_ENCODING);
            final FileOutputStream fos = new FileOutputStream(file);
            final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, PageUtils.CONTENT_ENCODING));
            template.merge(context, writer);
            writer.flush();
            writer.close();
            fos.close();
            log.info("\u751F\u6210\u6587\u4EF6\uFF1A" + file.getAbsolutePath());
        }
        catch (final Exception e) {
            log.error(e.getLocalizedMessage());
        }
    }
}
